package portada.server;

import java.net.URL;

import net.sf.hibernate4gwt.core.HibernateBeanManager;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static Logger log = Logger.getLogger(HibernateUtil.class.getName());

    private static final SessionFactory sessionFactory;
    private static final Object semaphore = new Object();

    static {
        synchronized (HibernateUtil.semaphore) {
            try {
                Configuration c = new Configuration(); 
            	URL url = HibernateUtil.class.getResource("/hibernate/hibernate.cfg.xml");
                Configuration a = c.configure(url);
                //new SchemaValidator(a);                
                sessionFactory = a.buildSessionFactory();
                HibernateBeanManager.getInstance().setSessionFactory(sessionFactory);
            } catch (HibernateException ex) {
                log.fatal("No se pudo configurar el hibernate: " + ex.toString());
                throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage(), ex);
            }
            log.debug("Hibernate Configurado.");
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    @SuppressWarnings("unchecked")
	public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            log.debug("currentSession: Creando la sesion.");
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

}
